package com.song.flowable.util;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * mybatis-plus代码生成器
 */
public class MysqlCodeGeneratorUtil {
    private static String tables = "process_category";
    private static String author = "song";
    private static String username = "root";
    private static String password = "Song512!";
    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/flowable?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&allowPublicKeyRetrieval=true";
    private static String parent = "com.song.flowable";
    private static String bussinessType = "process";
    private static String controller = parent + ".controller." + bussinessType;
    private static String service = parent + ".service." + bussinessType;
    private static String serviceImpl = parent + ".service.impl." + bussinessType;
    private static String mapper = parent + ".mapper." + bussinessType;
    private static String entity = parent + ".entity." + bussinessType;
    private static String moduleName = "";
    private final static String projectPath = System.getProperty("user.dir");
    private final static String modulePath = projectPath + File.separator + moduleName;
    private final static String codePath = modulePath + "/src/main/java/";
    private final static String resourcePath = modulePath + "/src/main/resources/";
    private final static String xmlPath = resourcePath + "/mapper/" + bussinessType;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //创建代码生成器
        AutoGenerator generator = new AutoGenerator();
        //配置全局
        customGlobalConfig(generator);
        //配置数据源
        customDatasourceConfig(generator);
        //配置包
        customPackageConfig(generator);
        //配置模板
        customTemplateConfig(generator);
        //配置策略
        customStrategyConfig(generator);
        //配置引擎
        generator.setTemplateEngine(new FreemarkerTemplateEngine());
//        generator.setTemplateEngine(new VelocityTemplateEngine());
        generator.execute();
    }

    private static void customPackageConfig(AutoGenerator generator) throws NoSuchFieldException, IllegalAccessException {
        //配置包，根据项目情况自定义生成代码的存放路径
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent(parent);
        Map<String, String> pathInfo = new HashMap<>();
        pathInfo.put(ConstVal.CONTROLLER_PATH, codePath + controller.replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.SERVICE_PATH, codePath + service.replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH, codePath + serviceImpl.replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.MAPPER_PATH, codePath + mapper.replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.ENTITY_PATH, codePath + entity.replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.XML_PATH, xmlPath);
        packageConfig.setPathInfo(pathInfo);

        Map<String, String> packageInfo = new HashMap<>();
        packageInfo.put(ConstVal.CONTROLLER, controller);
        packageInfo.put(ConstVal.SERVICE, service);
        packageInfo.put(ConstVal.SERVICE_IMPL, serviceImpl);
        packageInfo.put(ConstVal.MAPPER, mapper);
        packageInfo.put(ConstVal.ENTITY, entity);
        ConfigBuilder configBuilder = new ConfigBuilder(generator.getPackageInfo(), generator.getDataSource(), generator.getStrategy(), generator.getTemplate(), generator.getGlobalConfig());
        Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
        packageInfoField.setAccessible(true);
        packageInfoField.set(configBuilder, packageInfo);
        generator.setPackageInfo(packageConfig);
    }

    private static void customTemplateConfig(AutoGenerator generator){
        //配置模板
        TemplateConfig templateConfig = new TemplateConfig();
//        templateConfig.setXml(null);
//        templateConfig.setEntity(null);
//        templateConfig.setMapper(null);
//        templateConfig.setService(null);
//        templateConfig.setServiceImpl(null);
//        templateConfig.setController(controllerTemplatePath);
        generator.setTemplate(templateConfig);
    }

    private static void customStrategyConfig(AutoGenerator generator){
        //配置策略
        StrategyConfig strategyConfig = new StrategyConfig();
        //配置lombok模式，实体类加lombok注解
        strategyConfig.setEntityLombokModel(true);
        //配置表名与实体名的转换策略
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        //配置表字段名与实体属性名的转换策略
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        //配置REST风格控制器
        strategyConfig.setRestControllerStyle(true);
        //配置同时生成的表
        strategyConfig.setInclude(tables.split(","));
        //配置驼峰转连字符
        strategyConfig.setControllerMappingHyphenStyle(true);
        //配置表前缀
        strategyConfig.setTablePrefix(null);
        strategyConfig.setEntityTableFieldAnnotationEnable(true);
        generator.setStrategy(strategyConfig);
    }

    private static void customDatasourceConfig(AutoGenerator generator){
        //配置数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        //数据库类型
        dataSourceConfig.setDbType(DbType.MYSQL);
        //用户名
        dataSourceConfig.setUsername(username);
        //密码
        dataSourceConfig.setPassword(password);
        //驱动
        dataSourceConfig.setDriverName(driver);
        //URL
        dataSourceConfig.setUrl(url);
        generator.setDataSource(dataSourceConfig);
    }

    private static void customGlobalConfig(AutoGenerator generator){
        //全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        //设置生成代码文件输出路径
        globalConfig.setOutputDir(projectPath + File.separator + moduleName + "/src/main/java");
        //设置作者
        globalConfig.setAuthor(author);
        //设置是否打开目录
        globalConfig.setOpen(false);
        //设置实体是否加swagger2的注解
        globalConfig.setSwagger2(true);
        //设置service的名字，默认带I，设置%sService则为 表名+Service
        globalConfig.setServiceName("%sService");
        //配置日期LocalDate LocalDateTime
        globalConfig.setDateType(DateType.TIME_PACK);
        //开启文件覆盖
        globalConfig.setFileOverride(true);
        //开启二级缓存
        globalConfig.setEnableCache(false);
        //不需要ActiveRecord特性设置成false
        globalConfig.setActiveRecord(true);
        //开启XML文件生成BaseResultMap
        globalConfig.setBaseResultMap(true);
        //开启XML文件生成BaseColumnList
        globalConfig.setBaseColumnList(true);
        generator.setGlobalConfig(globalConfig);
    }
}
